package com.dsj.gxrd.modules.people.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsj.gxrd.modules.people.domain.dto.RdUserInfoDto;
import com.dsj.gxrd.modules.people.domain.entity.RdUserInfo;
import com.dsj.gxrd.modules.people.domain.query.RdUserInfoQuery;
import com.dsj.gxrd.modules.people.domain.vo.RdUserInfoVo;
import com.dsj.gxrd.modules.people.mapper.RdUserInfoMapper;
import com.dsj.gxrd.modules.people.service.RdUserInfoService;
import com.dsj.gxrd.utils.BaseEntityHandlerUtils;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author songpin566
 * @date 2023/09/21
 **/
@Service
public class RdUserInfoServiceImpl extends ServiceImpl<RdUserInfoMapper, RdUserInfo> implements RdUserInfoService {

    @Autowired
    private RemoteUserService remoteUserService;


    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<RdUserInfoVo> list(RdUserInfoQuery userInfoQuery) {
        return this.baseMapper.selectListByQuery(userInfoQuery);
    }

    @DS("master")
    @Override
    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional
    public AjaxResult add(RdUserInfoDto userInfoDto) {
        SysUser user = new SysUser();
        String phonenumber = userInfoDto.getPhonenumber();
        user.setUserName(phonenumber);
        user.setPassword(phonenumber);
        user.setDeptId(userInfoDto.getDeptId());
        //用户的角色
        user.setRoleIds(userInfoDto.getRoleIds().toArray(new Long[]{}));
        user.setNickName(userInfoDto.getName());
        AjaxResult result = remoteUserService.add(user);
        if ((int) result.get(AjaxResult.CODE_TAG) == Constants.FAIL) {
            return AjaxResult.error(result.get(AjaxResult.MSG_TAG).toString());
        }
        R<LoginUser> r = remoteUserService.getUserInfo(phonenumber, SecurityConstants.INNER);
        if (r.getCode() == Constants.FAIL) {
            return AjaxResult.error(r.getMsg());
        }
        RdUserInfo rdUserInfo = BeanUtils.copyProperties(userInfoDto, RdUserInfo.class);
        BaseEntityHandlerUtils.fastSetBaseEntity(rdUserInfo, SecurityUtils.getLoginUser(),false);
        rdUserInfo.setUserId(r.getData().getSysUser().getUserId());
        rdUserInfo.setDelFlag(0);
        rdUserInfo.setStatus(0);
        return save(rdUserInfo) ? AjaxResult.success() : AjaxResult.error("新增机构人员失败");
    }

    @Override
    public RdUserInfoVo selectUserById(Long userId) {
        return this.baseMapper.selectUserById(userId);
    }

    @Override
    public AjaxResult edit(RdUserInfoDto userInfoDto) {
        SysUser user = new SysUser();
        user.setUserName(userInfoDto.getPhonenumber());
        user.setNickName(userInfoDto.getName());
        user.setDeptId(userInfoDto.getDeptId());
        user.setUserId(userInfoDto.getUserId());
        user.setRoleIds(userInfoDto.getRoleIds().toArray(new Long[]{}));
        AjaxResult result = remoteUserService.edit(user);
        if ((int) result.get(AjaxResult.CODE_TAG) == Constants.FAIL) {
            throw new ServiceException(result.get(AjaxResult.MSG_TAG).toString());
        }
        //修改基础信息
        RdUserInfo rdUserInfo = BeanUtils.copyProperties(userInfoDto, RdUserInfo.class);
        BaseEntityHandlerUtils.fastSetBaseEntity(rdUserInfo, SecurityUtils.getLoginUser(),true);
        LambdaQueryWrapper<RdUserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RdUserInfo::getUserId, userInfoDto.getUserId());
        return update(rdUserInfo, wrapper) ? AjaxResult.success() : AjaxResult.error("修改机构人员失败");
    }

    @Override
    public AjaxResult removes(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return AjaxResult.error("请选择要删除的数据");
        }
        AjaxResult result = remoteUserService.remove(userIds.toArray(new Long[]{}));
        if ((int) result.get(AjaxResult.CODE_TAG) == Constants.FAIL) {
            return AjaxResult.error(result.get(AjaxResult.MSG_TAG).toString());
        }
        return this.lambdaUpdate()
                .in(RdUserInfo::getUserId, userIds).remove() ? AjaxResult.success() : AjaxResult.error("删除机构人员失败");
    }

    @Override
    public List<String> getUserInfoNamesByIds(Collection<Long> userIds) {
        List<RdUserInfo> list = this.lambdaQuery().select(RdUserInfo::getName).in(RdUserInfo::getUserId,userIds).list();
        if(CollectionUtils.isNotEmpty(list)){
            return list.stream().map(RdUserInfo::getName).collect(Collectors.toList());
        }
        return new ArrayList<>(0);
    }

}
